package com.anjia.plugin.bugly;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.tencent.bugly.crashreport.CrashReport;

import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * AnjiaFlutBuglyPlugin
 */
public class AnjiaFlutBuglyPlugin implements FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "anjia_flut_bugly");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        switch (call.method) {
            case NativeMethodId.postException:
                postException(call);
                result.success(null);
                break;
            default:
                result.notImplemented();

        }
    }

    private void postException(MethodCall call) {
        String type = "";
        String message = "";
        String detail = "";
        Map data = null;//追加到bugly跟踪数据extraMessage.txt中
        if (call.hasArgument("type")) {
            type = call.argument("type");
        }
        if (call.hasArgument("message")) {
            message = call.argument("message");
        }
        if (call.hasArgument("stackTrace")) {
            detail = call.argument("stackTrace");
        }
        if (call.hasArgument("data")) {
            data = call.argument("data");
        }
        try {
            CrashReport.postException(8, type, message, detail, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
